require([ 'angular', 'require', 'jquery' ], function(angular, require, $) {
	'use strict';
	jQuery.ajaxSetup({
		cache : false
	});
	var modalServiceDelegate

	var sc = angular.module('sc')
	var baseUrl = require.toUrl('.') + '../';
	sc.constant('pathPrefix', baseUrl);
	sc.run(function(pathPrefix, $rootScope) {
		$rootScope.$pathPrefix = pathPrefix;
	})
	configBaseView.$inject = [ '$stateProvider', '$urlRouterProvider', 'pathPrefix', '$controllerProvider' ]
	function configBaseView($stateProvider, $urlRouterProvider, pathPrefix, $controllerProvider) {
		$urlRouterProvider.otherwise("/home");// 默认转向到home
		$stateProvider.state('home', {
			url : '/home',
			templateUrl : pathPrefix + 'home.html'
		})
		$controllerProvider.allowGlobals && $controllerProvider.allowGlobals()
	}
	configAdminView.$inject = [ '$stateProvider', '$urlRouterProvider', 'pathPrefix' ]
	function configAdminView($stateProvider, $urlRouterProvider, pathPrefix) {
		var pf = pathPrefix + 'template'
		// for manager
		$stateProvider.state('examine', {
			url : '/manager/examine',
			params : {
				initType : ''
			},
			templateUrl : pf + '/manager/examine.html'
		})
		$stateProvider.state('examineStudent', {
			url : '/manager/examine/:student',
			templateUrl : pf + '/manager/examineStudent.html'
		})
		$stateProvider.state('printScore', {
			url : '/manager/printScore',
			templateUrl : pf + '/manager/printScore.html'
		})
		$stateProvider.state('queryScore', {
			url : '/manager/queryScore',
			templateUrl : pf + '/manager/queryScore.html'
		})
		$stateProvider.state('scoreStatistics', {
			url : '/manager/scoreStatistics',
			templateUrl : pf + '/manager/scoreStatistics.html'
		})
		$stateProvider.state('scoreAnalysis', {
			url : '/manager/scoreAnalysis',
			templateUrl : pf + '/manager/scoreAnalysis.html'
		})
		$stateProvider.state('view', {
			url : '/manager/view/:uid/:forPrint',
			templateUrl : pf + '/manager/view_sc.html'
		})
		$stateProvider.state('publicity', {
			url : '/publicity',
			templateUrl : pf + '/exps/report.html'
		})
	}
	configSysAdminView.$inject = [ '$stateProvider', '$urlRouterProvider', 'pathPrefix' ]
	function configSysAdminView($stateProvider, $urlRouterProvider, pathPrefix) {
		var pf = pathPrefix + 'template'
		// for manager
		$stateProvider.state('manageAdmin', {
			url : '/manager/manageAdmin',
			templateUrl : pf + '/manager/manageAdmin.html'
		})
		$stateProvider.state('report', {
			url : '/manager/report',
			templateUrl : pf + '/manager/report.html'
		})
	}
	configStudentView.$inject = [ '$stateProvider', '$urlRouterProvider', 'pathPrefix' ]
	function configStudentView($stateProvider, $urlRouterProvider, pathPrefix) {
		var pf = pathPrefix + 'template'
		$stateProvider.state('mysc', {
			url : '/mysc',
			templateUrl : pf + '/student/mysc.html'
		})
		$stateProvider.state('edit_sc', {
			url : '/edit_sc',
			params : {
				catalog : ''
			},
			templateUrl : pf + '/student/edit_sc.html'
		})
		$stateProvider.state('view_sc', {
			url : '/view_sc',
			params : {
				catalog : ''
			},
			templateUrl : pf + '/student/view_sc.html'
		})
		$stateProvider.state('publicity', {
			url : '/publicity',
			templateUrl : pf + '/exps/report.html'
		})
	}
	LoginCtrl.$inject = [ '$http', 'modalService', 'pathPrefix' ]
	function LoginCtrl($http, modalService, pathPrefix) {
		var ctrl = this;
		this.login = function(u, p) {
			ctrl.error = ''
			if (!u) {
				ctrl.error = '请输入用户名'
				return;
			}
			if (!p) {
				ctrl.error = '请输入密码'
				return;
			}
			return $http.post(':sc:login/login', {
				username : u,
				password : p
			}).success(function(r) {
				if (r === '') {
					ctrl.error = '用户名或密码错误'
					return;
				}
				if (r != '') {// 登录成功后到index.html
					location.href = (pathPrefix + 'index.html')
				}
				return r;
			});
		}
		this.logout = function() {// 注销成功后到index.html
			return $http.post(':sc:login/logout').success(function(r) {
				location.href = (pathPrefix + 'home.html')
			})
		}
	}
	sc.controller('LoginCtrl', LoginCtrl)

	configHttp.$inject = [ '$httpProvider', 'pathPrefix', '$sceProvider' ]
	function configHttp($httpProvider, pathPrefix, $sceProvider) {
		$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
		$httpProvider.defaults.headers.common['Cache-Control'] = 'no-cache';
		$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';
		var param = function(obj) {
			var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
			for (name in obj) {
				value = obj[name];
				if (value instanceof Array) {
					for (i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value instanceof Object) {
					for (subName in value) {
						subValue = value[subName];
						fullSubName = name + '.' + subName;
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value !== undefined && value !== null && value !== '')
					query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
			}
			return query.length ? query.substr(0, query.length - 1) : query;
		}
		$httpProvider.defaults.transformRequest = [ function(data) {
			return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
		} ]
		$httpProvider.interceptors.push('GlobalInterceptor');
	}

	GlobalInterceptor.$inject = [ 'pathPrefix', '$q' ];
	function GlobalInterceptor(pathPrefix, $q) {
		var urlReg = /((^\#(\w+)\#)|(^\:(\w+)\:))(.*)/;
		var request = function(config) {
			var u = config.url;
			var s = u.charAt(0);
			if (s != '#' && s != ':') {
				return config;
			}
			var r = u.match(urlReg)
			if (r) {
				var p = r[3] || r[5];
				config.url = pathPrefix + r[6];
			}
			return config;
		}
		var requestError = function(rejection) {
			modalServiceDelegate.error('请求失败', 1000)
			return $q.reject(rejection);
		}

		return {
			'request' : request,
			'responseError' : requestError
		}
	}
	sc.factory('GlobalInterceptor', GlobalInterceptor)
	sc.config(configHttp)
	sc.run(function(modalService) {
		modalServiceDelegate = modalService
	})
	$.post(baseUrl + 'login/getCurrent').done(function(e) {
		var r = e[0];
		sc.run(function($rootScope) {
			$rootScope.$availableRoles = e[1]
			$rootScope.$seletedRole = e[2];
			$rootScope.$user = r
			if (!r) {
				location.href = pathPrefix + 'index.html'
			}
		})
		sc.config(configBaseView)
		if (r.type == 0) {
			sc.config(configStudentView)
		} else if (r.type > 0) {
			sc.config(configAdminView)
		}
		if (r.type >= 2) {
			sc.config(configSysAdminView)
		}
		angular.element(document).ready(function() {
			angular.bootstrap(document, [ 'sc' ]);
		});
	})
	sc.run(function(pathPrefix, $rootScope, $location) {
		$rootScope.switchRole = function(selectRoleId) {
			debugger
			console.log($rootScope.$pathPrefix + "login/switchRole?toRole=" + selectRoleId);
			location.href = ($rootScope.$pathPrefix + "login/switchRole?toRole=" + selectRoleId);
			return true;
		}
	})
	return angular;
})
